package com.situ.mall.controller.back;

import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.situ.mall.entity.Category;
import com.situ.mall.entity.Product;
import com.situ.mall.entity.Result;
import com.situ.mall.service.ICategoryService;
import com.situ.mall.service.IProductService;

@Controller
@RequestMapping("/product")
public class ProductController {
	@Autowired
	private IProductService productService;
	@Autowired
	private ICategoryService categoryService;

	@RequestMapping("/selectAll.action")
	@ResponseBody
	public List<Product> selectAll() {
		System.out.println("ProductController.selectAll()");
		return productService.selectAll();
	}
	
	@RequestMapping("/getProductListPage.action")
	public String getProductListPage() {
		return "product_list";
	}
	
	// /product/selectByPage.action?page=1&limit=10&id=26&name=Apple&price=9991
	@RequestMapping("/selectByPage.action")
	@ResponseBody
	public Result slectByPage(@RequestParam(defaultValue = "1")Integer page, @RequestParam(defaultValue = "5")Integer limit, Product product) {
		System.out.println("ProductController.slectByPage()");
		Result result = productService.selectByPage(page, limit, product);
		return result;
	}
	
	@RequestMapping("/deleteAll.action")
	@ResponseBody
	public Result deleteAll(/* String ids */ Integer[] ids) {
		// System.out.println("ids: " + ids);
		// String[] array = ids.split(",");
		System.out.println(Arrays.toString(ids));// [26, 27]
		boolean isSuccess = productService.deleteAll(ids);
		if (isSuccess) {
			return Result.success("删除成功");
		} else {
			return Result.error("删除失败");
		}
	}
	
	@RequestMapping("/deleteById.action")
	@ResponseBody
	public Result deleteById(Integer id) {
		System.out.println("id: " + id);
		boolean isSuccess=productService.deleteById(id);
		if (isSuccess) {
			return Result.success("删除成功");
		} else {
			return Result.error("删除失败");
		}
	}
	
	@RequestMapping("/getProductInsertPage.action")
	public String getProductInsertPage(Model model) {
		List<Category> topCategoryList = categoryService.selectTopCategoryList();
		model.addAttribute("topCategoryList", topCategoryList);
		return "product_insert";
	}
	
	@RequestMapping("/insert.action")
	@ResponseBody
	public Result insert(Product product) {
		boolean isSuccess = productService.insert(product);
		if (isSuccess) {
			return Result.success("插入成功");
		} else {
			return Result.error("插入失败");
		}
	}
	
	
}